package com.myapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.myapp.domain.Emp;
import com.myapp.service.EmpService;
import com.myapp.validator.EmpValidator;

@Controller
@RequestMapping("/emp/insert.do")
public class EmpFormController {

	@Autowired
	private EmpService empService;

	@RequestMapping(method=RequestMethod.GET)
	public String form(@ModelAttribute("emp") Emp emp) {
		return "emp/empform";
	}
	
	@ModelAttribute("emp")
	public Emp formBacking(HttpServletRequest request) {
		Emp emp = new Emp();
		String empnoStr =request.getParameter("empno");
		if(empnoStr != null) {
			int empno =  Integer.parseInt(empnoStr);
			emp = empService.selectEmp(empno);
		}
		if(request.getMethod().equalsIgnoreCase("GET")) {
			emp.setEmpnoList(empService.getAllEmpno());
			emp.setDeptList(empService.getAllDepts());
		}
		return emp;
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String submit(@Valid Emp emp, BindingResult result) {
		if(result.hasErrors()) {
			System.out.println(result.toString());
			emp.setDeptList(empService.getAllDepts());
			emp.setEmpnoList(empService.getAllEmpno());
			return "emp/empform";
		}
		empService.updateEmp(emp);
		return "redirect:/emp/insert.do?empno="+emp.getEmpno();
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setValidator(new EmpValidator());
	}
}
